<template>
    <a-modal
      :visible="visible"
      width="1000px"
      :title="title"
      :okText="okText"
      @cancel="() => { $emit('cancel') }"
      @ok="submit()"
    >
    <!-- () => { $emit('create') } -->
    <a-form :form="form">
        <a-form-item
            label="供应商"
            :labelCol="{lg: {span: 5}, sm: {span: 7}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
            >
            <a-select
            v-model="serverName"
            :disabled="currentIndex != -1"
            show-search
                name="id"
                placeholder="请选择供应商费率"
                @change="handleServiceChange">
                <a-select-option
                v-for="item in feeOptions"
                :disabled="item.disabled"
                :key="item.id"
                :value="item.serverName">
                {{ item.serverName }}
                </a-select-option>
            </a-select>
        </a-form-item>
        <a-form-item
            label="价格列表"
            :labelCol="{lg: {span: 5}, sm: {span: 7}}"
            :wrapperCol="{lg: {span: 17}, sm: {span: 17} }"
            >
            <a-table
            v-show="priceTable.length"
            :columns="priceColumns"
            rowKey="amountLow"
            :pagination="false"
            :data-source="priceTable"
            size="small"
          >
            <span
              slot="feeRateType"
              slot-scope="text">
              <span>{{ text == 1 ? '固定' : '阶梯' }}</span>
            </span>
            <span
              slot="feeMode"
              slot-scope="text">
              <span>{{ text == 1 ? '开票金额' : '实发金额' }}</span>
            </span>
            <span
              slot="feeRate"
              slot-scope="text, record, index">
              <span v-if="record.feeRateType == 1">{{ text }}%</span>
              <a-button size="small" type="primary" v-if="record.feeRateType == 2"
              style="font-size: 12px;"
              @click="feeRateRangeList = record.feeRateList,genIndex = index,tableVisible = true"
              >查看费率</a-button>
            </span>
            <span
              slot="taxRate"
              slot-scope="text">
              <span v-if="text && text != '*'">{{ parseFloat((text*100).toPrecision(12)) }}%</span>
              <span v-else>{{ text }}</span>
            </span>
            <span
              slot="action"
              slot-scope="text, record, index">
              <template>
                <a @click="editPrice(record, index)">编辑</a>
              </template>
              <a-divider type="vertical" />
              <template >
                <a @click="deleteFeeTableRow(index)">删除</a>
              </template>
               
              
            </span>
          </a-table>
          <a-button type="primary" icon="plus"
          :disabled="priceTable.length > 3"
          @click="addPrice()">新增价格</a-button>
          <price-form ref="priceForm" @finishPrice="finishPrice"></price-form>
        </a-form-item>
      </a-form>
      <a-modal :visible="tableVisible"
        width="800px"
        title="阶梯费率"
        okText="确定"
        @cancel="tableVisible = false"
        @ok="tableVisible = false">
        <a-table
            :columns="feeRateRangeColumns"
            rowKey="amountLow"
            :pagination="false"
            :data-source="feeRateRangeList"
            size="small"
          >
            <span
              slot="money"
              slot-scope="text">
              <span>{{ text | formatMoney }}</span>
            </span>
            <span
              slot="rate"
              slot-scope="text">
              <span>{{ parseFloat((text*100).toPrecision(12)) }}%</span>
            </span>
            <span
              slot="action"
              slot-scope="text, record, index">
              <template>
                <a @click="editFeeRate(record, index)">编辑</a>
              </template>
              <a-divider type="vertical" />
              <template >
                <a @click="deleteFeeRangeRow(index)">删除</a>
              </template>
            </span>
          </a-table>
          <collection-create-form
            ref="collectionForm"
            :visible="collectionFormVisable"
            @cancel="handleCollectionCancel"
            @create="handleCollectionCreate"
          />
      </a-modal>
    </a-modal>
  </template>
  <script>
  import {getFeeList, getXbdConcatList, getXbdServers, getServerFeeList} from '@/api/manage'
  import priceForm from './priceForm'
  import CollectionCreateForm from './feeRange-Form'
  export default {
    components: {
      priceForm,
      CollectionCreateForm
    },
    props: {
      visible: {
        type: Boolean,
        default: false
      }
    },
    data () {
        return {
          tableVisible: false,
            feeOptions: [],
            arr: [],
            serverName: undefined,
            serverId: '',
            feeRate: '',
            feeRateType: 1,
            feeMode: 2,
            collectionFormVisable: false,
            feeRateRangeList: [],
            feeRangeValidator: {
              status: 'error'
            },
            feeRateRangeColumns: [
              {
                title: '最低金额',
                dataIndex: 'amountLow',
                scopedSlots: { customRender: 'money' }
              },
              {
                title: '最高金额',
                dataIndex: 'amountHigh',
                scopedSlots: { customRender: 'money' }
              },
              {
                title: '服务费率',
                dataIndex: 'feeRate',
                scopedSlots: { customRender: 'rate' }
              },
              {
                title: '操作',
                dataIndex: 'action',
                scopedSlots: { customRender: 'action' }
              }
            ],
            currentIndex: -1,
            title: '新增价格',
            okText: '新增',
            priceTable: [],
            priceColumns: [
              {
                title: '费率类型',
                dataIndex: 'feeRateType',
                scopedSlots: { customRender: 'feeRateType' },
                width: 100
              },
              {
                title: '账单方式',
                dataIndex: 'feeMode',
                scopedSlots: { customRender: 'feeMode' },
                width: 100
              },
              {
                title: '服务费率',
                dataIndex: 'feeRate',
                scopedSlots: { customRender: 'feeRate' },
                width: 100
              },
              {
                title: '税率',
                dataIndex: 'taxRate',
                scopedSlots: { customRender: 'taxRate' },
                width: 80
              },
              {
                title: '操作',
                dataIndex: 'action',
                scopedSlots: { customRender: 'action' },
                width: 100
              }
            ],
            xbdParams: {},
            xbdServerUuid: '',
            genIndex: -1
        }
    },
    beforeCreate () {
      this.form = this.$form.createForm(this, { name: 'form_in_modal' })
    },
    mounted () {
      this.currentIndex = -1
        // this.getFeeLists()
    },
    methods: {
      resetForm () {
        this.serverName = undefined
        this.serverId = undefined
        this.priceTable = []
      },
      editFeeRate (info, index) {
        this.collectionFormVisable = true

        this.$refs.collectionForm.edit(info, index)
        
      },
      edit (info, index) {
        if (index != -1) {
          this.title = '修改供应商费率'
          this.okText = '保存'
          this.serverName = info.serverName
        this.serverId = info.serverId
        this.feeRate = info.feeRate
        this.feeRateType = info.feeRateType
        this.feeMode = info.feeMode
        if (info.feeRateList) {
          this.feeRateRangeList = info.feeRateList
        }
        this.currentIndex = index
        }
       
      },
      checkMinMax (rule, value, callback, source, options) {
        if (value <= this.form.getFieldValue('amountLow')) {
          callback(new Error('不应低于最低金额'))
        } else {
          callback()
        }
      },
      getServers (list) {
        getXbdServers().then(res => {
            console.log(res)
            this.feeOptions = res.resData
            this.feeOptions.forEach((item,index) => {
                this.$set(this.feeOptions[index], 'disabled', false)
            })
            this.checkList(list)
        }).catch(err => {
            console.log(err)
        })
      },
      checkList (list) {
        if (list) {
          console.log(list)
          console.log(this.feeOptions)
          this.feeOptions.forEach((item,index) => {
            list.forEach(item1 => {
              if (item1.serverName == item.serverName) {
                console.log('8u8u8u')
                this.$set(this.feeOptions[index], 'disabled', true)
              }
            })
          })
          // console.log(this.feeOptions)
        }
      },
      getInfo (info, editInfo, index) {
        console.log(info)
        if (info.isOpenXbd) {
          this.xbdParams = info
        }
        if (editInfo) {
          console.log(editInfo)
          this.serverId = editInfo.serverId
          if (!editInfo.serverName) {
            getServerFeeList({serverId: this.serverId}).then(res => {
              this.serverName = res.resData.serverName
              this.xbdServerUuid = res.resData.serverUuid
            })
          } else {
            this.serverName = editInfo.serverName
          }
          this.priceTable = editInfo.priceTable
          this.currentIndex = index
          this.title = '编辑供应商费率'
          this.okText = '修改'
        } else {
          this.currentIndex = -1
          this.serverName = undefined
          this.serverId = ''
          this.title = '新增供应商费率'
          this.okText = '新增'
          this.priceTable = []
        }
        // console.log('ihao实际  ')
       
        // this.feeMode = 2
       
        // this.feeRate = ''
        
       
      },
      handleServiceChange (e) {
        console.log(e)
        console.log(this.feeRate)
        this.feeOptions.forEach((i,index) => {
            if (e == i.serverName) {
                // const obj = {}
                this.serverId = i.id
                this.xbdServerUuid = i.serverUuid
                // obj.feeMode = i.feeMode
                // obj.feeRateType = i.feeRateType
                // obj.feeRate = this.feeRate
                this.serverName = i.serverName
                // this.arr.push(obj)
            }
        })
      },
      submit () {
        console.log(this.priceTable)
        // return
        console.log(this.feeRateRangeList)
        if (this.serverName == undefined) {
          this.$message.error('请选择供应商！')
          return
        }

        
        // if (this.feeRateType == 2) {
        //   if (this.feeRateRangeList.length > 0) {
        //     infoObj = {
        //       serverId: this.serverId,
        //       serverName: this.serverName,
        //       feeMode: this.feeMode,
        //       feeRateType: this.feeRateType,
        //       feeRateList: []
        //     }
        //     this.feeRateRangeList.forEach(i => {
        //       const obj = {
        //         amountLow: i.amountLow,
        //         amountHigh: i.amountHigh,
        //         feeRate: i.feeRate
        //       }
        //       infoObj.feeRateList.push(obj)
        //     })
        //   } else {
        //     this.$message.error('请先添加阶梯费率！')
        //     return
        //   }
        // } else {
        //   if (!this.feeRate) {
        //     this.$message.error('请输入服务费率！')
        //     return
        //   }
        //   console.log(this.feeRate)
        //   infoObj = {
        //     serverId: this.serverId,
        //     feeRate: this.feeRate,
        //     feeMode: this.feeMode,
        //     serverName: this.serverName,
        //     feeRateType: this.feeRateType
        //   }
        //   // arr.push(obj)
        // }
        if (this.priceTable.length == 0) {
          this.$message.error('请添加价格！')
          return
        }
        let check = true
        this.priceTable.forEach(item => {
          
          if (item.feeRateType == 2) {
            console.log(item)
            if (item.feeRateList.length == 0) {
              check = false
            }
          }
        })
        if (!check) {
          this.$message.error('请添加阶梯费率！')
          return
        }
        const obj = {
          serverId: this.serverId,
          serverName: this.serverName,
          priceTable: this.priceTable
        }
        this.$emit('create',obj, this.currentIndex)
        console.log(obj)
        this.serverName = undefined
        this.feeRate = ''
        this.feeRateRangeList = []
        this.currentIndex = -1
        this.priceTable = []
      },
      setFeeRateType(event) {
        this.feeRateType = event.target.value
      },
      handleCollectionCancel() {
        this.$refs.collectionForm.form.resetFields()
        this.collectionFormVisable = false
      },
      handleCollectionCreate(index) {
        const form = this.$refs.collectionForm.form
        form.validateFields((err, values) => {
          if (err) {
            return
          }
          console.log(values)
         console.log(index)
          const arrayLength = this.feeRateRangeList.length
          if (index == -1) {
            if (
            arrayLength &&
            values.amountHigh * 100 !== this.feeRateRangeList[0].amountLow &&
            values.amountLow * 100 !== this.feeRateRangeList[arrayLength - 1].amountHigh
          ) {
            this.$message.error('请确保费率区间连续')
            return
          }
          }
          
          // console.log('Received values of form: ', values)
          values.amountHigh *= 100
          values.amountLow *= 100
          values.feeRate /= 100
          if (index == -1) {
          this.feeRateRangeList.push(values)

          } else {
            this.feeRateRangeList[index] = values
          }
          this.feeRateRangeList.sort((a, b) => a.amountLow - b.amountLow)
          form.resetFields()
          this.checkFeeRange()
          this.collectionFormVisable = false
        })
      },
      showCollectionModel() {
        this.collectionFormVisable = true
        this.$refs.collectionForm.add()
      },
      checkFeeRange() {
        if (this.feeRateRangeList.length) {
          this.feeRangeValidator = {
            help: '',
            status: 'success'
          }
        } else {
          this.feeRangeValidator = {
            help: '请添加阶梯费率',
            status: 'error'
          }
        }
      },
      deleteFeeRangeRow(index) {
        console.log(index)
        this.feeRateRangeList.splice(index, 1)
        // if (this.feeRateRangeList.length == 0) {
        //   this.gen
        // }
      },
      deleteFeeTableRow (index) {
        this.priceTable.splice(index, 1)
      },
      addPrice () {
        if (!this.serverName) {
          this.$message.error('请选择供应商！')
          return
        }
        // getXbdServerUuid({serverId: this.serverId}).then(res => {
        //   console.log(res)
        // })
        this.xbdParams.xbdServerUuid = this.xbdServerUuid
        const arr = []
        let str = ''
        this.priceTable.forEach(item => {
          arr.push(item.taxRate)
        })
        str = arr.join(',')
        this.$refs.priceForm.show(this.xbdParams, str)
      },
      editPrice (info, index) {
        this.xbdParams.xbdServerUuid = this.xbdServerUuid
        const arr = []
        let str = ''
        this.priceTable.forEach((item, index1) => {
          if (index1 != index) {
            arr.push(item.taxRate)
          }
        })
        str = arr.join(',')
        this.$refs.priceForm.show(this.xbdParams, str, info, index)
      },
      finishPrice (infoObj, currentIndex) {
        console.log(infoObj)
        console.log(currentIndex)
        if (currentIndex == -1) {
          this.priceTable.push(infoObj)
        } else {
          this.$set(this.priceTable, currentIndex, infoObj)
          // this.priceTable[currentIndex] = infoObj
        }
      }
    }
  }
  </script>
  